package com.hospital.hospitalsystem.modules.hospital.task;

import com.hospital.hospitalsystem.modules.hospital.dao.entity.DoctorOrderDetailEntity;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.DoctorOrderEntity;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.QuartzCronEntity;
import com.hospital.hospitalsystem.modules.hospital.dto.DoctorOrderDetailReq;
import com.hospital.hospitalsystem.modules.hospital.service.DoctorOrderDetailService;
import com.hospital.hospitalsystem.modules.hospital.service.DoctorOrderService;
import com.hospital.hospitalsystem.modules.hospital.service.QuartzCronService;
import com.hospital.hospitalsystem.modules.login.dao.entity.DoctorEntity;
import com.hospital.hospitalsystem.modules.login.service.DoctorService;
import com.hospital.hospitalsystem.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.Calendar;
import java.util.stream.Collectors;

/**
 * @author qiancheng@cqxyy.net
 * @date 2023/2/23
 */
@Component
@Slf4j
public class DoctorOrderDetail implements InterruptableJob {

    @Autowired
    private DoctorOrderService doctorOrderService;

    @Autowired
    private DoctorOrderDetailService doctorOrderDetailService;

    @Autowired
    private QuartzCronService quartzCronService;

    @Autowired
    private DoctorService doctorService;

    @Override
    public void interrupt() throws UnableToInterruptJobException {

    }

    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 本次执行时间
        Date lastExecuteTime = jobExecutionContext.getFireTime();
        // 下一次任务时间
        Date nexExecuteTime = jobExecutionContext.getNextFireTime();
        // 运行状态
        boolean runStatus = true;

        String hospitalUuid = jobExecutionContext.getMergedJobDataMap().getString("hospitalUuid");
        Example exampleQuartzCron = new Example(QuartzCronEntity.class);
        Example.Criteria criteriaQuartzCron = exampleQuartzCron.createCriteria();
        criteriaQuartzCron.andEqualTo("hospitalUuid",hospitalUuid);
        QuartzCronEntity quartzCronEntity = quartzCronService.selectByExample(exampleQuartzCron).get(0);
        boolean flag = false;
        // 判断当前周是否已经执行过任务
        if (quartzCronEntity.getLastTime() != null) {
            Instant instant = quartzCronEntity.getLastTime().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localDate = instant.atZone(zoneId).toLocalDate();
            flag = isCurrentWeek(localDate);
        }
        if (!flag) {
            //更改任务状态
            quartzCronEntity = new QuartzCronEntity();
            quartzCronEntity.setLastTime(lastExecuteTime);
            quartzCronService.updateByExampleSelective(quartzCronEntity,exampleQuartzCron);

            Example exampleDoctor = new Example(DoctorEntity.class);
            Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
            criteriaDoctor.andEqualTo("hospitalUuid",hospitalUuid);
            criteriaDoctor.andEqualTo("type","doctor");
            criteriaDoctor.andEqualTo("status",1);
            List<String> doctorUuid = doctorService.selectByExample(exampleDoctor).stream().map(s -> s.getUuid()).collect(Collectors.toList());

            Example example = new Example(DoctorOrderEntity.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("hospitalUuid",hospitalUuid);
            criteria.andIn("doctorUuid",doctorUuid);
            List<DoctorOrderEntity> list = doctorOrderService.selectByExample(example);
            Date now = new Date();
//            Example exampleDetail = new Example(DoctorOrderDetailEntity.class);
//            Example.Criteria criteriaDetail = exampleDetail.createCriteria();
//            criteriaDetail.andEqualTo("hospitalUuid",hospitalUuid);
//            criteriaDetail.andGreaterThan("date",now);
//            int result = doctorOrderDetailService.deleteByExample(exampleDetail);
//            if (result > 0){
//                //TODO 清除预约订单表
//            }
            for (DoctorOrderEntity doctorOrderEntity : list){
                Date nextWeek = TimeUtils.getNextWeekDate(now,doctorOrderEntity.getDay());
                DoctorOrderDetailEntity tmp = new DoctorOrderDetailEntity();
                BeanUtils.copyProperties(doctorOrderEntity,tmp);
                //统一每天时间 方便group by
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(nextWeek);
                calendar.set(Calendar.HOUR,-12);
                calendar.set(Calendar.MINUTE,0);
                calendar.set(Calendar.SECOND,0);
                calendar.set(Calendar.MILLISECOND,0);
                tmp.setDate(calendar.getTime());
                tmp.setSurplus(doctorOrderEntity.getTotal());
                tmp.setId(null);
                tmp.setDetailUuid(UUID.randomUUID().toString());
                doctorOrderDetailService.insertSelective(tmp);
            }
        }
        runStatus = false;
        log.info("医院" + hospitalUuid + "定时任务执行完成!");
    }

    /**
     * 判断当前时间是否是当前周
     * @param date
     * @return
     */
    public boolean isCurrentWeek(LocalDate date) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前周第一天（周一）
        LocalDate firstDayOfWeek = currentDate.with(DayOfWeek.MONDAY);
        // 获取当前周最后一天（周日）
        LocalDate lastDayOfWeek = currentDate.with(DayOfWeek.SUNDAY);
        // 判断给定日期是否在当前周内
        return date.isAfter(firstDayOfWeek.minusDays(1)) && date.isBefore(lastDayOfWeek.plusDays(1));
    }
}
